package com.treeroot.treenet.business;

import com.treeroot.treenet.config.ConfigUtil;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.nio.ByteBuffer;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Description: TCP客户端
 * Create By TreeRoot
 * Create Time: 2025/06/02 07:56
 * Class Name: TcpClient
 *
 * @author TreeRoot
 */
public class TcpClient {

    public static void main(String[] args) {
        String serverIp = "127.0.0.1";
        int serverPort = ConfigUtil.getTcpPort();

        short magic = (short) 0xCAFE;
        byte version = 1;
        // UTF-8 编码
        byte encoding = 1;

        while (true) {
            try (Socket socket = new Socket(serverIp, serverPort)) {
                OutputStream out = socket.getOutputStream();
                InputStream in = socket.getInputStream();

                String timestamp = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
                String message = "hello TreeNet " + timestamp;

                // 构造请求
                byte[] messageBytes = message.getBytes(StandardCharsets.UTF_8);
                ByteBuffer buffer = ByteBuffer.allocate(2 + 1 + 1 + 4 + messageBytes.length);
                buffer.putShort(magic);
                buffer.put(version);
                buffer.put(encoding);
                buffer.putInt(messageBytes.length);
                buffer.put(messageBytes);
                out.write(buffer.array());
                out.flush();

                // 读取响应（阻塞）
                byte[] header = new byte[8];
                int read = 0;
                while (read < 8) {
                    int r = in.read(header, read, 8 - read);
                    if (r == -1) {
                        System.err.println("连接关闭");
                        return;
                    }
                    read += r;
                }

                ByteBuffer respBuffer = ByteBuffer.wrap(header);
                short respMagic = respBuffer.getShort();
                byte respVersion = respBuffer.get();
                byte respEncoding = respBuffer.get();
                int respLen = respBuffer.getInt();

                if (respMagic != magic) {
                    System.err.println("响应魔数不匹配！");
                    continue;
                }

                byte[] payload = new byte[respLen];
                int total = 0;
                while (total < respLen) {
                    int r = in.read(payload, total, respLen - total);
                    if (r == -1) {
                        break;
                    }
                    total += r;
                }

                String respStr = new String(payload, StandardCharsets.UTF_8);
                System.out.println("收到响应：" + respStr);

            } catch (Exception e) {
                System.err.println("连接或通信异常: " + e.getMessage());
            }

            try {
                // 每毫秒发送一次
                Thread.sleep(1);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                break;
            }
        }
    }
}